package com.gexiaobao.pigeon.ui.fragment.mine.organization.detail

import android.graphics.Color
import android.os.Bundle
import android.view.View
import android.view.ViewGroup
import androidx.core.view.isVisible
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseFragment
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.ext.loadListData
import com.gexiaobao.pigeon.app.ext.loadServiceInit
import com.gexiaobao.pigeon.app.ext.showLoading
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.Util
import com.gexiaobao.pigeon.app.weight.recycleview.SpaceItemDecoration
import com.gexiaobao.pigeon.databinding.FragmentShedNoticeBinding
import com.gexiaobao.pigeon.ui.activity.ActivityRaceRanking
import com.gexiaobao.pigeon.ui.adapter.AnnouncementAdapter
import com.gexiaobao.pigeon.ui.adapter.MessageListAdapter
import com.gexiaobao.pigeon.ui.fragment.mine.organization.activity.ActivityAnnouncementDetail
import com.gexiaobao.pigeon.viewmodel.OrgDetailViewModel
import com.gexiaobao.pigeon.viewmodel.SharedViewModel
import com.kingja.loadsir.core.LoadService
import com.yanzhenjie.recyclerview.OnItemMenuClickListener
import com.yanzhenjie.recyclerview.SwipeMenuCreator
import com.yanzhenjie.recyclerview.SwipeMenuItem
import me.hgj.jetpackmvvm.ext.nav
import me.hgj.jetpackmvvm.ext.navigateAction
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2023/5/31 16:10
 * @Describe    : 我的组织-公告
 */
class FragmentShedNotice : BaseFragment<OrgDetailViewModel, FragmentShedNoticeBinding>() {

    private var lockOrgId = ""
    private var mRaceName = ""
    private var mRaceId = 0

    private val ruleAdapter: AnnouncementAdapter by lazy { AnnouncementAdapter(arrayListOf()) }
    private val mAdapter: MessageListAdapter by lazy { MessageListAdapter(arrayListOf()) }
    private lateinit var loadsir: LoadService<Any>
    private var viewModel: SharedViewModel? = null

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        viewModel = ViewModelProvider(requireActivity())[SharedViewModel::class.java]
        lockOrgId = requireArguments().getInt("orgId", 0).toString()
        mRaceId = requireArguments().getInt("raceId", 0)
        mRaceName = requireArguments().getString("raceName").toString()
        mDatabind.tvNotice.isSelected = true
        val orgDescribe = requireArguments().getString("orgDescribe")
        mDatabind.tvOrgIntro.text = orgDescribe
    }

    override fun initView(savedInstanceState: Bundle?) {
        val swipeMenuCreator = SwipeMenuCreator { _, rightMenu, _ ->
            val width = resources.getDimensionPixelSize(R.dimen.dp_70)
            val height = ViewGroup.LayoutParams.MATCH_PARENT
            val deleteItem = SwipeMenuItem(activity)
                .setBackground(R.drawable.round_b_g_5_train_fly_list_delete_red)
                .setTextColor(Color.WHITE)
                .setText(R.string.delete)
                .setTextSize(15)
                .setWidth(width)
                .setHeight(height)
            rightMenu.addMenuItem(deleteItem)
        }
        mDatabind.layoutList.swipeRecyclerView.setSwipeMenuCreator(swipeMenuCreator)

        val mItemMenuClickListener = OnItemMenuClickListener { menuBridge, position ->
            /** 任何操作必须先关闭菜单，否则可能出现Item菜单打开状态错乱 */
            menuBridge.closeMenu()
            /** 左侧还是右侧菜单 */
//            val direction = menuBridge.direction
//            /**  菜单在Item中的Position */
//            val menuPosition = menuBridge.position
            /** 调用删除接口 */
            showLoading(getString(R.string.loading))
            mViewModel.deleteMessage(mAdapter.data[position].id.toString())
        }
        mDatabind.layoutList.swipeRecyclerView.setOnItemMenuClickListener(mItemMenuClickListener)
        mDatabind.layoutList.swipeRecyclerView.init(LinearLayoutManager(context), mAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 1f))
        )

        mDatabind.listShed.swipeRecyclerView.init(LinearLayoutManager(context), ruleAdapter).addItemDecoration(
            SpaceItemDecoration(0, Util.dp2px(context, 10f))
        )

        //状态页配置
        loadsir = loadServiceInit(mDatabind.layoutList.swipeRecyclerView) {
            //点击重试时触发的操作
            loadsir.showLoading()
            mViewModel.getMessageList(true, "1", lockOrgId)
            mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
        }

        mDatabind.layoutList.swipeRefreshLayout.init {
            loadsir.showLoading()
            mViewModel.getMessageList(true, "1", lockOrgId)
            mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
        }

        mAdapter.setOnItemClickListener { _, _, position ->
            nav().navigateAction(R.id.action_org_to_notice_detail, Bundle().apply {
                putInt("id", mAdapter.data[position].id)
            })
        }

        ruleAdapter.setOnItemClickListener { _, _, position ->
            startActivity<ActivityAnnouncementDetail>("id" to ruleAdapter.data[position].id.toString())
        }
    }

    override fun lazyLoadData() {
        super.lazyLoadData()
        loadsir.showLoading()
        mViewModel.getMessageList(true, "1", lockOrgId)
        mViewModel.getRegulationAnnouncementList(true, lockOrgId.toInt())
    }

    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(mDatabind.btnRanking, mDatabind.tvNotice, mDatabind.tvRegulation, mDatabind.tvOrgDetail) {
            when (it) {
                mDatabind.tvNotice -> selectedUiState(1)
                mDatabind.tvRegulation -> selectedUiState(2)
                mDatabind.tvOrgDetail -> selectedUiState(3)
                mDatabind.btnRanking -> {
                    startActivity<ActivityRaceRanking>("title" to mRaceName, "raceId" to mRaceId)
                    activity?.overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out)
                }
            }
        }
    }

    override fun createObserver() {
        super.createObserver()
        /** 获取规程公告列表（app端） */
        mViewModel.regulationAnnouncementResult.observe(viewLifecycleOwner) {
            loadListData(it, ruleAdapter, loadsir, mDatabind.listShed.swipeRecyclerView, mDatabind.listShed.swipeRefreshLayout)
        }
        /**  消息列表  */
        mViewModel.messageList.observe(viewLifecycleOwner) {
            if (it.isSuccess) {
                loadListData(it, mAdapter, loadsir, mDatabind.layoutList.swipeRecyclerView, mDatabind.layoutList.swipeRefreshLayout)
            } else {
                RxToast.showToast(it.errMessage)
            }
        }

        /** 删除消息 */
        mViewModel.deleteMsgResult.observe(viewLifecycleOwner) {
            dismissLoading()
            if (it.isSuccess) {
                loadsir.showLoading()
                mViewModel.getMessageList(true, "1", lockOrgId)
            } else {
                RxToast.showToast(it.errorMsg)
            }
        }
    }

    private fun selectedUiState(i: Int) {
        when (i) {
            1 -> {
                mDatabind.tvNotice.isSelected = true
                mDatabind.tvRegulation.isSelected = false
                mDatabind.tvOrgDetail.isSelected = false
                mDatabind.layoutList.conList.isVisible = true
                mDatabind.listShed.conList.isVisible = false
                mDatabind.tvOrgIntro.isVisible = false
            }

            2 -> {
                mDatabind.tvNotice.isSelected = false
                mDatabind.tvRegulation.isSelected = true
                mDatabind.tvOrgDetail.isSelected = false
                mDatabind.layoutList.conList.isVisible = false
                mDatabind.listShed.conList.isVisible = true
                mDatabind.tvOrgIntro.isVisible = false
            }

            else -> {
                mDatabind.tvNotice.isSelected = false
                mDatabind.tvRegulation.isSelected = false
                mDatabind.tvOrgDetail.isSelected = true
                mDatabind.layoutList.conList.isVisible = false
                mDatabind.listShed.conList.isVisible = false
                mDatabind.tvOrgIntro.isVisible = true
            }
        }
    }

    companion object {
        fun newInstance(raceId: Int, orgId: Int, raceName: String, orgDescribe: String): FragmentShedNotice {
            val fragment = FragmentShedNotice()
            val bundle = Bundle()
            bundle.putInt("raceId", raceId)
            bundle.putInt("orgId", orgId)
            bundle.putString("raceName", raceName)
            bundle.putString("orgDescribe", orgDescribe)
            fragment.arguments = bundle
            return fragment
        }
    }
}